package com.fastloan.mgt.model.service.arithmetic.tobacco;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fastloan.mgt.application.base.model.Application;
import com.fastloan.mgt.application.base.util.ApplicationPDF;
import com.fastloan.mgt.application.contract.model.ApplicationContract;
import com.fastloan.mgt.customer.model.ZyCustomer;
import com.fastloan.mgt.model.annotation.ModelClass;
import com.fastloan.mgt.model.model.ApplicationModel;
import com.fastloan.mgt.model.model.vo.TobaccoModelVo;
import com.fastloan.mgt.model.service.GeneratorModelStrategy;
import com.fastloan.mgt.processcontrol.base.model.ProcessSession;
import com.fastloan.mgt.processcontrol.base.service.ProcessDispatcher;
import com.fastloan.mgt.product.basics.model.Product;
import com.fastloan.mgt.product.basics.service.ProductService;
import com.fastloan.mgt.verify.enums.ApiStore;
import com.fastloan.mgt.verify.util.ApiCall;
import com.fastloan.mgt.verify.util.ApiUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Optional;
import java.util.function.Consumer;

import static com.fastloan.mgt.verify.util.ApiUtil.KX_SUCCESS_CODE;

/**
 * 烟草贷模型
 *
 * @author yanwe
 * createTime 2017-12-2017/12/13 17:55
 */
@Component
@ModelClass(modelName = "烟草贷模型",modelId = 2)
public class TobaccoCreditModelCalculate extends GeneratorModelStrategy {

    @Autowired
    private ProductService productService;

    public TobaccoCreditModelCalculate() {
        codeFieldMap.put(62,"enterpriseName");
        codeFieldMap.put(181,"creditCode");
        codeFieldMap.put(182,"name");
        codeFieldMap.put(183,"personId");
        codeFieldMap.put(82,"address");
        codeFieldMap.put(53,"loanPurpose");
    }

    @Override
    public void calculate(String applicationId, Consumer<ApplicationModel> applicationModelConsumer) {
        Application application = getApplicationInfo(applicationId);
        ZyCustomer customerInfo = getCustomerInfo(application.getCustomerId());
        Product product = productService.selectByPrimaryKey(application.getProductId());
        TobaccoCreditModel tobaccoCreditModel = new TobaccoCreditModel();
        tobaccoCreditModel.setSerialNumber(applicationId);
        tobaccoCreditModel.setSceneCode("ZXCJ");//TODO:未知属性
        tobaccoCreditModel.setAmount(application.getApplyAmount().intValue());
        tobaccoCreditModel.setRepaymentTimeLimit(application.getApplyPeriod());
        tobaccoCreditModel.setRepaymentWay(ApplicationPDF.getRepayment(product.getRepayment()));
        tobaccoCreditModel.setMobileNum(customerInfo.getPhoneNum());
        convertIPC2Model(tobaccoCreditModel,getApplicationIPC(applicationId));
        ProcessSession processSession = ProcessDispatcher.getProcessSession(application.getProcessId());
        String creditReportSessionId = processSession.getAttribute("creditReportSessionId", String.class);
        String tobaccoVerifyId = processSession.getAttribute("tobaccoVerifyId", String.class);
        tobaccoCreditModel.setCreditReportSessionId(creditReportSessionId);
        tobaccoCreditModel.setTobaccoVerifyId(tobaccoVerifyId);
        ApiUtil.sendJsonAsync(JSON.toJSONString(tobaccoCreditModel), ApiStore.BBD_TOBACCO_MODEL
                , this::reCall
                ,(apiCall,apiResult) -> {
                    if(!apiResult.getRet().equals(KX_SUCCESS_CODE)){
                        logger.error("烟草贷模型评估失败！code:"+apiResult.getRet()+"msg:"+apiResult.getMsg());
                    }
                    JSONObject jsonObject = JSON.parseObject(apiResult.getData());
                    Integer status = jsonObject.getInteger("status");
                    String message = jsonObject.getString("message");
                    if (status != 200){
                        logger.error("烟草贷模型评估失败！code:"+status+"msg:"+message);
                    }
                });
    }

    @Override
    public void sendBack(ApplicationContract applicationContract, boolean isPass) {
        TobaccoModelVo tobaccoModelVo = new TobaccoModelVo();
        tobaccoModelVo.setCreditLine(Optional.ofNullable(applicationContract.getLoanAmount())
                .orElse(BigDecimal.ZERO));
        tobaccoModelVo.setInterestRate(Optional.ofNullable(applicationContract.getLoanMonthRate())
                .orElse(BigDecimal.ZERO));
        tobaccoModelVo.setPassed(isPass);
        tobaccoModelVo.setSerialNumber(applicationContract.getApplicationId());
        tobaccoModelVo.setManualApproval(true);
        tobaccoModelVo.setRepaymentTimeLimit(Optional.ofNullable(applicationContract.getCreditPeriod()).orElse(0));
        Application application = applicationService.selectByPrimaryKey(applicationContract.getApplicationId());
        Product product = productService.selectByPrimaryKey(application.getProductId());
        tobaccoModelVo.setRepaymentWay(ApplicationPDF.getRepayment(product.getRepayment()));
        tobaccoModelVo.setReason("");
        ApiUtil.sendJsonAsync(JSON.toJSONString(tobaccoModelVo), ApiStore.BBD_TOBACCO_MODEL_SEND_RESULT
                , apiCall -> logger.info("BBD结果回执失败！"+application.getApplicationId())
                ,(apiCall, apiResult) -> logger.info("BBD结果回执成功！result:"+apiResult));
    }

    private void reCall(ApiCall apiCall) {
        try {
            Thread.sleep(1800 * 1000);//半小时重试一次
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        apiCall.reCall();
    }
}
